package com.zenchn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zenchn.annotation.OperLog;
import com.zenchn.entity.*;
import com.zenchn.enums.*;
import com.zenchn.exception.CheckException;
import com.zenchn.exception.CustomException;
import com.zenchn.external.service.FileGenericStrategy;
import com.zenchn.model.*;
import com.zenchn.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 代理商信息管理控制器
 *
 * @author panbingqi
 * @date 2021-06-04 17:34
 */
@RestController
@RequestMapping(value = "agentManageWeb")
@Api(value = "代理商信息管理模块相关接口", tags = "信息管理-代理商信息管理")
@RequiresPermissions("information:manage:agent")
public class AgentManageWebController {
    private final String MODULE = "信息管理>代理商信息管理";

    @Resource
    private RegionService regionService;

    @Resource
    private RegionDetailService regionDetailService;

    @Resource
    private CustomerContactsService customerContactsService;

    @Resource
    private CustomerVisitService customerVisitService;

    @Resource
    private CustomerService customerService;

    @Resource
    private FileGenericStrategy fileGenericStrategy;

    @Resource
    private AreasService areasService;

    @Resource
    private AccountService accountService;

    @Resource
    private CustomerUpgradeService customerUpgradeService;

    @Resource
    private CustomerTransferService customerTransferService;


    /**
     * 分页获取代理商信息管理列表
     *
     * @param keyword
     * @param regionId
     * @param areasCode
     * @param accountId
     * @param level
     * @param startTime
     * @param endTime
     * @param page
     * @param pageSize
     * @param request
     * @param response
     * @return
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "分页获取代理商信息管理列表")
    @ApiOperation(value = "分页获取代理商信息管理列表", notes = "分页获取代理商信息管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "关键字"),
            @ApiImplicitParam(dataType = "String", name = "regionId", value = "所属大区"),
            @ApiImplicitParam(dataType = "String", name = "areasCode", value = "所属省份"),
            @ApiImplicitParam(dataType = "String", name = "accountId", value = "所属用户"),
            @ApiImplicitParam(dataType = "Integer", name = "level", value = "等级"),
            @ApiImplicitParam(dataType = "Date", name = "startTime", value = "参数名称，开始时间"),
            @ApiImplicitParam(dataType = "Date", name = "endTime", value = "参数名称，结束时间"),
            @ApiImplicitParam(dataType = "Integer", name = "page", value = "当前第page页"),
            @ApiImplicitParam(dataType = "Integer", name = "pageSize", value = "每页pageSize数量")
    })
    @GetMapping(value = "/list")
    @RequiresPermissions("information:manage:agent")
    public ResponseEntity<HttpDataResult<PageInfo>> list(
            @RequestParam(required = false, value = "keyword") String keyword,
            @RequestParam(required = false, value = "regionId") String regionId,
            @RequestParam(required = false, value = "areasCode") String areasCode,
            @RequestParam(required = false, value = "accountId") String accountId,
            @RequestParam(required = false, value = "level") Integer level,
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
            @RequestParam(required = false, value = "page", defaultValue = "1") Integer page,
            @RequestParam(required = false, value = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpDataResult<PageInfo> result = new HttpDataResult<>(request.getRequestURI());

        final TMiAccountExtend accountExtend = (TMiAccountExtend) request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        if (accountExtend == null) {
            throw new CustomException("当前登入账户无数据权限");
        }
        //获取当前登入用户所属省份数据权限
        List<String> areasCodeList = new ArrayList<>();
        if (accountExtend.getRegionCode() != null && !"".equals(accountExtend.getRegionCode().trim())) {
            areasCodeList = getAreasCodeList(accountExtend.getRegionCode().trim());
        }
        if (accountExtend.getAreasCode() != null && !"".equals(accountExtend.getAreasCode()) && !areasCodeList.contains(accountExtend.getAreasCode())) {
            areasCodeList.add(accountExtend.getAreasCode().trim());
        }
        //取交集
        List<String> resultList = new ArrayList<>();
        if (regionId != null && !"".equals(regionId.trim())) {
            List<String> codeList = getAreasCodeList(regionId);
            for (String code : areasCodeList) {
                if (codeList.contains(code)) {
                    resultList.add(code);
                }
            }
        } else {
            resultList.addAll(areasCodeList);
        }

        if (resultList.isEmpty()) {
            result.setData(new PageInfo());
        } else {
            LocalDateTime startDate = null;
            if (startTime != null) {
                startDate = LocalDateTime.of(startTime, LocalTime.MIN);
            }
            LocalDateTime endDate = null;
            if (endTime != null) {
                endDate = LocalDateTime.of(endTime, LocalTime.MAX);
            }

            PageHelper.startPage(page, pageSize);
            PageInfo pageInfo = new PageInfo(customerService.selectAgentDynamicSqlByParameter(keyword, resultList, areasCode, accountId, level, startDate, endDate));

            List<TMiCustomer> customerList = pageInfo.getList();
            List<CustomerVO> customerVOList = new ArrayList<>();
            for (TMiCustomer customer : customerList) {
                CustomerVO customerVO = new CustomerVO();
                BeanUtils.copyProperties(customer, customerVO);
                //设置区域名称
                TMiRegionDetailExample regionDetailExample = new TMiRegionDetailExample();
                regionDetailExample.createCriteria().andAreasCodeEqualTo(customer.getAreasCode()).andRegionIdNotEqualTo(RegionEnum.NATIONAL_ADMINISTRATIVE_REGION.getId());

                List<String> regionIdList = regionDetailService.selectByExample(regionDetailExample).stream().map(TMiRegionDetail::getRegionId).collect(Collectors.toList());
                if (regionIdList != null && !regionIdList.isEmpty()) {
                    TMiRegionExample regionExample = new TMiRegionExample();
                    regionExample.createCriteria().andRegionIdIn(regionIdList);

                    customerVO.setRegionName(regionService.selectByExample(regionExample).stream().map(TMiRegion::getRegionName).collect(Collectors.joining(",")));
                }
                //设置省级名称
                TSysAreas areas = areasService.selectByPrimaryKey(customer.getAreasCode());
                if (areas != null) {
                    customerVO.setAreasCodeName(areas.getName());
                }
                //设置默认联系人信息
                TMiCustomerContactsExample customerContactsExample = new TMiCustomerContactsExample();
                customerContactsExample.createCriteria().andCustomerIdEqualTo(customer.getCustomerId()).andIsDefaultEqualTo("1");

                List<TMiCustomerContacts> customerContactsList = customerContactsService.selectByExample(customerContactsExample);
                if (customerContactsList != null && !customerContactsList.isEmpty()) {
                    TMiCustomerContacts customerContacts = customerContactsList.get(0);
                    customerVO.setCustomerContacts(customerContacts);
                }
                //设置所属用户名称
                TSysAccount account = accountService.selectByPrimaryKey(customer.getAccountId());
                if (account != null) {
                    customerVO.setAccountName(account.getRealName());
                }

                customerVOList.add(customerVO);
            }

            pageInfo.setList(customerVOList);

            result.setData(pageInfo);
        }

        result.setMessage("获取代理商管理信息列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 获取省份信息
     *
     * @param regionId
     * @return
     */
    private List<String> getAreasCodeList(String regionId) {
        List<String> areasCodeList = new ArrayList<>();
        TMiRegionDetailExample regionDetailExample = new TMiRegionDetailExample();
        regionDetailExample.createCriteria().andRegionIdEqualTo(regionId);

        List<TMiRegionDetail> regionDetailList = regionDetailService.selectByExample(regionDetailExample);
        if (regionDetailList != null && !regionDetailList.isEmpty()) {
            areasCodeList.addAll(regionDetailList.stream().map(TMiRegionDetail::getAreasCode).collect(Collectors.toList()));
        }
        return areasCodeList;
    }


    /***
     * 代理商管理信息详情 （修改页获取数据）
     * @param customerId
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "代理商管理信息详情 （修改页获取数据）")
    @ApiOperation(value = "代理商管理信息详情 （修改页获取数据）", notes = "代理商管理信息详情 （修改页获取数据）")
    @ApiImplicitParam(dataType = "String", name = "customerId", value = "客户ID", required = true)
    @GetMapping(value = "/detail")
    public ResponseEntity<HttpDataResult<Map<String, Object>>> detail(
            @RequestParam(value = "customerId") String customerId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Map<String, Object>> result = new HttpDataResult<>(request.getRequestURI());
        Map<String, Object> resultData = new HashMap<>(16);

        //获取代理商信息
        TMiCustomer customer = customerService.selectByPrimaryKey(customerId);
        if (customer == null) {
            throw new CheckException("该代理商不存在！");
        }
        CustomerVO customerVO = new CustomerVO();
        BeanUtils.copyProperties(customer, customerVO);
        //设置省级名称
        TSysAreas areas = areasService.selectByPrimaryKey(customer.getAreasCode());
        if (areas != null) {
            customerVO.setAreasCodeName(areas.getName());
        }
        //设置所属用户名称
        TSysAccount account = accountService.selectByPrimaryKey(customer.getAccountId());
        if (account != null) {
            customerVO.setAccountName(account.getRealName());
        }
        resultData.put("customerVO", customerVO);

        //获取联系人信息
        TMiCustomerContactsExample customerContactsExample = new TMiCustomerContactsExample();
        customerContactsExample.createCriteria().andCustomerIdEqualTo(customerId);

        List<TMiCustomerContacts> customerContactsList = customerContactsService.selectByExample(customerContactsExample);
        resultData.put("customerContactsList", customerContactsList);

        //获取拜访记录信息
        TMiCustomerVisitExample customerVisitExample = new TMiCustomerVisitExample();
        customerVisitExample.createCriteria().andCustomerIdEqualTo(customerId);
        customerVisitExample.setOrderByClause("visit_date desc");

        List<TMiCustomerVisit> customerVisitList = customerVisitService.selectByExample(customerVisitExample);
        List<CustomerVisitVO> customerVisitVOList = new ArrayList<>();
        if (customerVisitList != null && !customerVisitList.isEmpty()) {
            for (TMiCustomerVisit customerVisit : customerVisitList) {
                CustomerVisitVO customerVisitVO = new CustomerVisitVO();
                BeanUtils.copyProperties(customerVisit, customerVisitVO);

                TMiCustomerContacts customerContacts = customerContactsService.selectByPrimaryKey(customerVisit.getContactsId());
                if (customerContacts != null) {
                    //设置被拜访人名称
                    customerVisitVO.setVisitName(customerContacts.getContactsName());
                    //设置被拜访人电话
                    customerVisitVO.setVisitTel(customerContacts.getTelephone());
                    //设置拜访人名称
                    TSysAccount sysAccount = accountService.selectByPrimaryKey(customerVisit.getCreator());
                    if (sysAccount != null) {
                        customerVisitVO.setOperatorName(sysAccount.getRealName());
                    }
                }
                customerVisitVOList.add(customerVisitVO);
            }
        }
        resultData.put("customerVisitVOList", customerVisitVOList);

        //获取升降级日志信息
        TMiCustomerUpgradeExample customerUpgradeExample = new TMiCustomerUpgradeExample();
        customerUpgradeExample.createCriteria().andCustomerIdEqualTo(customerId);
        customerUpgradeExample.setOrderByClause("create_time desc");

        List<TMiCustomerUpgrade> customerUpgradeList = customerUpgradeService.selectByExample(customerUpgradeExample);
        List<CustomerUpgradeVO> customerUpgradeVOList = new ArrayList<>();
        if (customerUpgradeList != null && !customerUpgradeList.isEmpty()) {
            for (TMiCustomerUpgrade customerUpgrade : customerUpgradeList) {
                CustomerUpgradeVO customerUpgradeVO = new CustomerUpgradeVO();
                BeanUtils.copyProperties(customerUpgrade, customerUpgradeVO);
                //设置操作类型名称
                customerUpgradeVO.setUpgradeTypeName(UpgradeTypeEnum.getAppDesc(customerUpgrade.getUpgradeType()));
                //设置是否有效名称
                customerUpgradeVO.setIsEnableName(CustomerStatusEnum.getAppDesc(customerUpgrade.getIsEnable()));
                //设置升降级操作人名称
                TSysAccount sysAccount = accountService.selectByPrimaryKey(customerUpgrade.getCreator());
                if (sysAccount != null) {
                    customerUpgradeVO.setOperatorName(sysAccount.getRealName());
                }

                customerUpgradeVOList.add(customerUpgradeVO);
            }
        }
        //设置客户初始创建数据
        CustomerUpgradeVO customerUpgradeVO = new CustomerUpgradeVO();
        customerUpgradeVO.setUpgradeLevel(1);
        customerUpgradeVO.setUpgradeTypeName(UpgradeTypeEnum.CREATE_OPERATION.getAppDesc());
        customerUpgradeVO.setIsEnableName(CustomerStatusEnum.EFFECTIVE.getAppDesc());
        customerUpgradeVO.setCreateTime(customer.getCreateTime());
        //设置创建人名称
        TSysAccount upgradeAccount = accountService.selectByPrimaryKey(customer.getCreator());
        if (upgradeAccount != null) {
            customerUpgradeVO.setOperatorName(upgradeAccount.getRealName());
        }
        customerUpgradeVOList.add(customerUpgradeVO);

        resultData.put("customerUpgradeVOList", customerUpgradeVOList);

        //获取转移日志信息
        TMiCustomerTransferExample customerTransferExample = new TMiCustomerTransferExample();
        customerTransferExample.createCriteria().andCustomerIdEqualTo(customerId);
        customerTransferExample.setOrderByClause("create_time desc");

        List<TMiCustomerTransfer> customerTransferList = customerTransferService.selectByExample(customerTransferExample);
        List<CustomerTransferVO> customerTransferVOList = new ArrayList<>();
        if (customerTransferList != null && !customerTransferList.isEmpty()) {
            for (TMiCustomerTransfer customerTransfer : customerTransferList) {
                CustomerTransferVO customerTransferVO = new CustomerTransferVO();
                BeanUtils.copyProperties(customerTransfer, customerTransferVO);
                //设置转移前名称
                TSysAccount beforeAccount = accountService.selectByPrimaryKey(customerTransfer.getBeforeAccountId());
                if (beforeAccount != null) {
                    customerTransferVO.setBeforeAccountName(beforeAccount.getRealName());
                }
                //设置转移后名称
                TSysAccount afterAccount = accountService.selectByPrimaryKey(customerTransfer.getAfterAccountId());
                if (afterAccount != null) {
                    customerTransferVO.setAfterAccountName(afterAccount.getRealName());
                }
                //设置是否有效名称
                customerTransferVO.setIsEnableName(CustomerStatusEnum.getAppDesc(customerTransfer.getIsEnable()));
                //设置转移日志操作人名称
                TSysAccount sysAccount = accountService.selectByPrimaryKey(customerTransfer.getCreator());
                if (sysAccount != null) {
                    customerTransferVO.setOperatorName(sysAccount.getRealName());
                }

                customerTransferVOList.add(customerTransferVO);
            }
        }
        resultData.put("customerTransferVOList", customerTransferVOList);

        result.setData(resultData);
        result.setMessage("OK");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 导出代理商信息管理列表
     *
     * @param keyword
     * @param regionId
     * @param areasCode
     * @param accountId
     * @param level
     * @param startTime
     * @param endTime
     * @param request
     * @param response
     * @return
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "导出代理商信息管理列表")
    @ApiOperation(value = "导出代理商信息管理列表", notes = "导出代理商信息管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "关键字"),
            @ApiImplicitParam(dataType = "String", name = "regionId", value = "所属大区"),
            @ApiImplicitParam(dataType = "String", name = "areasCode", value = "所属省份"),
            @ApiImplicitParam(dataType = "String", name = "accountId", value = "所属用户"),
            @ApiImplicitParam(dataType = "Integer", name = "level", value = "等级"),
            @ApiImplicitParam(dataType = "Date", name = "startTime", value = "参数名称，开始时间", required = true),
            @ApiImplicitParam(dataType = "Date", name = "endTime", value = "参数名称，结束时间", required = true),
    })
    @GetMapping(value = "/export")
    @RequiresPermissions("information:manage:agent:export")
    public ResponseEntity<HttpDataResult<String>> export(
            @RequestParam(required = false, value = "keyword") String keyword,
            @RequestParam(required = false, value = "regionId") String regionId,
            @RequestParam(required = false, value = "areasCode") String areasCode,
            @RequestParam(required = false, value = "accountId") String accountId,
            @RequestParam(required = false, value = "level") Integer level,
            @RequestParam(value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
            @RequestParam(value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpDataResult<String> result = new HttpDataResult<>(request.getRequestURI());

        final TMiAccountExtend accountExtend = (TMiAccountExtend) request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        if (accountExtend == null) {
            throw new CustomException("当前登入账户无数据权限");
        }
        //获取当前登入用户所属省份数据权限
        List<String> areasCodeList = new ArrayList<>();
        if (accountExtend.getRegionCode() != null && !"".equals(accountExtend.getRegionCode().trim())) {
            areasCodeList = getAreasCodeList(accountExtend.getRegionCode().trim());
        }
        if (accountExtend.getAreasCode() != null && !"".equals(accountExtend.getAreasCode()) && !areasCodeList.contains(accountExtend.getAreasCode())) {
            areasCodeList.add(accountExtend.getAreasCode().trim());
        }
        //取交集
        List<String> resultList = new ArrayList<>();
        if (regionId != null && !"".equals(regionId.trim())) {
            List<String> codeList = getAreasCodeList(regionId);
            for (String code : areasCodeList) {
                if (codeList.contains(code)) {
                    resultList.add(code);
                }
            }
        } else {
            resultList.addAll(areasCodeList);
        }

        if (resultList.isEmpty()) {
            throw new CustomException("未查询到相关代理商信息，无法导出！");
        }

        LocalDateTime startDate = null;
        if (startTime != null) {
            startDate = LocalDateTime.of(startTime, LocalTime.MIN);
        }
        LocalDateTime endDate = null;
        if (endTime != null) {
            endDate = LocalDateTime.of(endTime, LocalTime.MAX);
        }

        PageInfo pageInfo = new PageInfo(customerService.selectAgentDynamicSqlByParameter(keyword, resultList, areasCode, accountId, level, startDate, endDate));

        List<TMiCustomer> customerList = pageInfo.getList();

        if (null == customerList || customerList.isEmpty()) {
            throw new CustomException("未查询到相关代理商信息，无法导出！");
        }

        List<CustomerVO> customerVOList = new ArrayList<>();
        for (TMiCustomer customer : customerList) {
            CustomerVO customerVO = new CustomerVO();
            BeanUtils.copyProperties(customer, customerVO);
            //设置区域名称
            TMiRegionDetailExample regionDetailExample = new TMiRegionDetailExample();
            regionDetailExample.createCriteria().andAreasCodeEqualTo(customer.getAreasCode()).andRegionIdNotEqualTo(RegionEnum.NATIONAL_ADMINISTRATIVE_REGION.getId());

            List<String> regionIdList = regionDetailService.selectByExample(regionDetailExample).stream().map(TMiRegionDetail::getRegionId).collect(Collectors.toList());
            if (regionIdList != null && !regionIdList.isEmpty()) {
                TMiRegionExample regionExample = new TMiRegionExample();
                regionExample.createCriteria().andRegionIdIn(regionIdList);

                customerVO.setRegionName(regionService.selectByExample(regionExample).stream().map(TMiRegion::getRegionName).collect(Collectors.joining(",")));
            }
            //设置省级名称
            TSysAreas areas = areasService.selectByPrimaryKey(customer.getAreasCode());
            if (areas != null) {
                customerVO.setAreasCodeName(areas.getName());
            }
            //设置默认联系人信息
            TMiCustomerContactsExample customerContactsExample = new TMiCustomerContactsExample();
            customerContactsExample.createCriteria().andCustomerIdEqualTo(customer.getCustomerId()).andIsDefaultEqualTo("1");

            List<TMiCustomerContacts> customerContactsList = customerContactsService.selectByExample(customerContactsExample);
            if (customerContactsList != null && !customerContactsList.isEmpty()) {
                TMiCustomerContacts customerContacts = customerContactsList.get(0);
                customerVO.setCustomerContacts(customerContacts);
            }

            customerVOList.add(customerVO);
        }

        //设置导出相关信息
        XSSFWorkbook wb = new XSSFWorkbook();

        XSSFSheet sheet = wb.createSheet("代理商信息管理");

        sheet.setColumnWidth(0, (30 * 256));
        sheet.setColumnWidth(1, (30 * 256));
        sheet.setColumnWidth(2, (20 * 256));
        sheet.setColumnWidth(3, (35 * 256));
        sheet.setColumnWidth(4, (40 * 256));
        sheet.setColumnWidth(5, (40 * 256));
        sheet.setColumnWidth(6, (18 * 256));
        sheet.setColumnWidth(7, (18 * 256));
        sheet.setColumnWidth(8, (18 * 256));
        sheet.setColumnWidth(9, (25 * 256));
        sheet.setColumnWidth(10, (12 * 256));


        XSSFRow row0 = sheet.createRow(0);
        row0.setHeightInPoints(28);

        XSSFFont tableHeaderFont = wb.createFont();
        tableHeaderFont.setFontHeightInPoints((short) 12);
        tableHeaderFont.setBold(true);
        XSSFCellStyle tableHeaderStyle = wb.createCellStyle();
        tableHeaderStyle.setFont(tableHeaderFont);
        // 下边框
        tableHeaderStyle.setBorderBottom(BorderStyle.THIN);
        // 左边框
        tableHeaderStyle.setBorderLeft(BorderStyle.THIN);
        // 右边框
        tableHeaderStyle.setBorderRight(BorderStyle.THIN);
        // 上边框
        tableHeaderStyle.setBorderTop(BorderStyle.THIN);
        tableHeaderStyle.setAlignment(HorizontalAlignment.CENTER);
        tableHeaderStyle.setVerticalAlignment(VerticalAlignment.CENTER);


        createCell(row0, 0, tableHeaderStyle, "创建时间");
        createCell(row0, 1, tableHeaderStyle, "所属区域");
        createCell(row0, 2, tableHeaderStyle, "所属省份");
        createCell(row0, 3, tableHeaderStyle, "公司名称");
        createCell(row0, 4, tableHeaderStyle, "地址");
        createCell(row0, 5, tableHeaderStyle, "主营");
        createCell(row0, 6, tableHeaderStyle, "联系人");
        createCell(row0, 7, tableHeaderStyle, "职位");
        createCell(row0, 8, tableHeaderStyle, "电话");
        createCell(row0, 9, tableHeaderStyle, "业务区域");
        createCell(row0, 10, tableHeaderStyle, "客户等级");


        XSSFFont fontBody = wb.createFont();
        fontBody.setFontHeightInPoints((short) 11);
        XSSFCellStyle styleBody = wb.createCellStyle();
        styleBody.setFont(fontBody);
        // 下边框
        styleBody.setBorderBottom(BorderStyle.THIN);
        // 左边框
        styleBody.setBorderLeft(BorderStyle.THIN);
        // 右边框
        styleBody.setBorderRight(BorderStyle.THIN);
        // 上边框
        styleBody.setBorderTop(BorderStyle.THIN);
        styleBody.setAlignment(HorizontalAlignment.CENTER);
        styleBody.setVerticalAlignment(VerticalAlignment.CENTER);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < customerVOList.size(); i++) {
            CustomerVO customerVO = customerVOList.get(i);

            XSSFRow trow = sheet.createRow(i + 1);
            trow.setHeightInPoints(24);
            createCell(trow, 0, styleBody, customerVO.getCreateTime().format(formatter));
            createCell(trow, 1, styleBody, customerVO.getRegionName());
            createCell(trow, 2, styleBody, customerVO.getAreasCodeName());
            createCell(trow, 3, styleBody, customerVO.getCustomerName());
            createCell(trow, 4, styleBody, customerVO.getCustomerAdress());
            createCell(trow, 5, styleBody, customerVO.getBusiness());
            createCell(trow, 6, styleBody, customerVO.getCustomerContacts() == null ? "" : customerVO.getCustomerContacts().getContactsName());
            createCell(trow, 7, styleBody, customerVO.getCustomerContacts() == null ? "" : customerVO.getCustomerContacts().getPost());
            createCell(trow, 8, styleBody, customerVO.getCustomerContacts() == null ? "" : customerVO.getCustomerContacts().getTelephone());
            createCell(trow, 9, styleBody, customerVO.getRegion());
            createCell(trow, 10, styleBody, String.valueOf(customerVO.getLevel()));
        }


        StringBuilder fileName = new StringBuilder();
        fileName.append("代理商信息管理");

        fileName.append("_").append(System.currentTimeMillis());

        //创建临时文件
        File excelFile = File.createTempFile(fileName.toString(), ".xlsx");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        FileCopyUtils.copy(baos.toByteArray(), new FileOutputStream(excelFile));

        //保存到临时OSS上
        JsonResult<String> jsonResult = fileGenericStrategy.simpleFileUploadTempBucket("downloadExport", excelFile, fileName + ".xlsx");

        // 删除临时文件
        excelFile.delete();

        if (!jsonResult.getSuccess()) {
            throw new CustomException(jsonResult.getData().toString());
        }


        result.setData(jsonResult.getData());
        result.setMessage("OK");
        result.setStatus(HttpStatus.OK.value());


        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 创建单元格
     *
     * @param row
     * @param column
     * @param style
     * @param value
     */
    private void createCell(XSSFRow row, int column, XSSFCellStyle style, String value) {
        XSSFCell cell = row.createCell(column);
        cell.setCellValue(new XSSFRichTextString(value));
        cell.setCellStyle(style);
    }

    /***
     *  删除代理商
     * @param customerId
     * @param request
     * @param response
     * @return
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.DELETE, detail = "删除代理商")
    @ApiOperation(value = "删除代理商", notes = "删除代理商")
    @ApiImplicitParam(dataType = "String", name = "customerId", value = "代理商id")
    @DeleteMapping(value = "/delete")
    @RequiresPermissions("information:manage:agent:delete")
    public ResponseEntity<HttpDataResult<Boolean>> delete(
            @RequestParam(value = "customerId") String customerId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());


        if (null == customerId || "".equals(customerId.trim())) {
            throw new CheckException("需要删除的代理商ID异常，删除操作失败！");
        }
        TMiCustomer customer = customerService.selectByPrimaryKey(customerId);
        if (customer == null) {
            throw new CheckException("需要删除的代理商ID异常，删除操作失败！");
        }
        //等级大于1级，不允许删除
        if (customer.getLevel() > CustomerLevelTypeEnum.ONE.getType()) {
            throw new CheckException("代理商等级大于1级，不允许删除！");
        }
        //跨月不能删除
        if (customer.getCreateTime().getMonthValue() != LocalDateTime.now().getMonthValue() || customer.getCreateTime().getYear() != LocalDateTime.now().getYear()) {
            throw new CheckException("无法删除跨月记录！");
        }
        //判断是否存在拜访记录
        TMiCustomerVisitExample customerVisitExample = new TMiCustomerVisitExample();
        customerVisitExample.createCriteria().andCustomerIdEqualTo(customerId);

        if (customerVisitService.countByExample(customerVisitExample) > 0) {
            throw new CheckException("已存在拜访记录，不允许删除！");
        }

        //删除客户表信息
        customerService.deleteByPrimaryKey(customerId);
        //删除联系人信息
        TMiCustomerContactsExample customerContactsExample = new TMiCustomerContactsExample();
        customerContactsExample.createCriteria().andCustomerIdEqualTo(customerId);

        customerContactsService.deleteByExample(customerContactsExample);
        //删除升降级记录信息
        TMiCustomerUpgradeExample customerUpgradeExample = new TMiCustomerUpgradeExample();
        customerUpgradeExample.createCriteria().andCustomerIdEqualTo(customerId);

        customerUpgradeService.deleteByExample(customerUpgradeExample);
        //删除所属权转移日志
        TMiCustomerTransferExample customerTransferExample = new TMiCustomerTransferExample();
        customerTransferExample.createCriteria().andCustomerIdEqualTo(customerId);

        customerTransferService.deleteByExample(customerTransferExample);

        result.setData(true);
        result.setMessage("OK");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

}

